package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.sys.models.bo.PermissionAssignBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.bo.SysRolePermissionBO;
import com.yt.sys.models.dto.SysRolePermissionDTO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录信息控制器
 *
 * @author lizicong
 * @Date 2025-10-25 00:30:21
 */

@RestController
@RequestMapping("/api/sysRolePermission")
@Slf4j
@Api(value = "SysRolePermissionApiController",tags = "登录信息Api接口")
public class SysRolePermissionApiController {

    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<SysRolePermissionDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        SysRolePermissionDTO dto = sysRolePermissionService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "登录信息列表",notes = "登录信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<SysRolePermissionDTO>> queryPageList(SysRolePermissionBO bo){
        Wrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<SysRolePermissionDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = sysRolePermissionService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    @ApiOperation(value = "为角色分配权限", notes = "为指定角色分配权限")
    @PostMapping("/assignPermissions")
    public Result<String> assignPermissions(@RequestBody PermissionAssignBO assignBO) {
        // 参数校验
        if (assignBO == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "请求参数不能为空");
        }

        if (assignBO.getRoleId() == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "角色ID不能为空");
        }

        if (assignBO.getPermissionIds() == null || assignBO.getPermissionIds().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "权限ID列表不能为空");
        }

        try {
            // 先删除该角色原有的所有权限关联记录
            EntityWrapper<SysRolePermissionDTO> deleteWrapper = new EntityWrapper<>();
            deleteWrapper.eq("role_id", assignBO.getRoleId());
            sysRolePermissionService.delete(deleteWrapper);

            // 批量插入新的角色权限关联记录
            for (Long permissionId : assignBO.getPermissionIds()) {
                SysRolePermissionDTO dto = new SysRolePermissionDTO();
                dto.setRoleId(assignBO.getRoleId());
                dto.setPermissionId(permissionId);
                sysRolePermissionService.insert(dto);
            }

            return new Result<>(CodeEnum.SUCCESS.getCode(), "分配成功");
        } catch (Exception e) {
            log.error("为角色分配权限时发生错误", e);
            return new Result<>(CodeEnum.FAIL.getCode(), "分配失败：" + e.getMessage());
        }
    }

    /**
     * 获取角色已分配的权限
     *
     * @param roleIdBO 包含角色ID的请求对象
     * @return 权限ID列表
     */
    @ApiOperation(value = "获取角色已分配的权限", notes = "获取指定角色已经分配的权限ID列表")
    @PostMapping("/getRolePermissions")
    public Result<List<Long>> getRolePermissions(@RequestBody RoleIdBO roleIdBO) {
        // 参数校验
        if (roleIdBO == null || roleIdBO.getRoleId() == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "角色ID不能为空");
        }

        try {
            // 查询该角色的所有权限关联记录
            EntityWrapper<SysRolePermissionDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("role_id", roleIdBO.getRoleId());
            List<SysRolePermissionDTO> rolePermissions = sysRolePermissionService.selectList(wrapper);

            // 提取权限ID列表
            List<Long> permissionIds = rolePermissions.stream()
                    .map(SysRolePermissionDTO::getPermissionId)
                    .collect(Collectors.toList());

            return new Result<>(CodeEnum.SUCCESS.getCode(), "查询成功", permissionIds);
        } catch (Exception e) {
            log.error("获取角色已分配权限时发生错误", e);
            return new Result<>(CodeEnum.FAIL.getCode(), "查询失败：" + e.getMessage());
        }
    }

    /**
     * 用于接收角色ID参数的BO类
     */
    @lombok.Data
    public static class RoleIdBO {
        private Long roleId;
    }
}
